package com.bsj.pay.controller.partner;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.bsj.pay.common.ExcelData;
import com.bsj.pay.common.Result;
import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.model.AreaBean;
import com.bsj.pay.model.ChargeAccountBean;
import com.bsj.pay.model.OrderBean;
import com.bsj.pay.model.PartnerBean;
import com.bsj.pay.service.AreaService;
import com.bsj.pay.service.ChargeAccountService;
import com.bsj.pay.service.OrderService;
import com.bsj.pay.service.PartnerService;
import com.bsj.pay.service.impl.OrderServiceImpl;
import com.bsj.pay.util.HttpUtil;
import com.bsj.pay.util.ResultUtil;
import com.bsj.pay.util.date.DateTimeUtil;
import com.bsj.pay.util.excel.ExcelUtil;
import com.bsj.pay.util.excel.ExportExcelUtil;
import com.bsj.pay.util.http.Http;
import com.bsj.pay.util.http.Http.Response;
import com.bsj.pay.util.security.MD5;
import com.bsj.pay.util.security.PassWrodsCreater;
import com.github.pagehelper.PageInfo;

import net.sf.json.JSONObject;

@RequestMapping("/partner/chargeAccount")
@Controller("partnerChargeAccountController")
public class ChargeAccountController {
	
	@Autowired
	private ChargeAccountService chargeAccountService;
	
	@Autowired
	private AreaService phoneAreaService;
	
	@Autowired
	private PartnerService partnerService;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/orderExport.html")
	public void  orderExport(HttpServletRequest req, HttpServletResponse res,ChargeAccountBean chargeAccount) throws Exception {
		ChargeAccountBean queryModel=new ChargeAccountBean();
		PartnerBean puser=(PartnerBean) req.getSession().getAttribute("puser");
		queryModel.setPartner_id(puser.getId());
		if(!StringUtils.isEmpty(chargeAccount.getAccount()))queryModel.setAccount(chargeAccount.getAccount());
		if(chargeAccount.getType()!=null)queryModel.setType(chargeAccount.getType());
		if(chargeAccount.getStatus()!=null)queryModel.setStatus(chargeAccount.getStatus());
		if(chargeAccount.getCharge_status()!=null)queryModel.setCharge_status(chargeAccount.getCharge_status());
		if(chargeAccount.getNotify_status()!=null)queryModel.setNotify_status(chargeAccount.getNotify_status());
		List<ChargeAccountBean> lists=chargeAccountService.queryList(queryModel);
		 ExcelData data = new ExcelData();
	     data.setName("充值列表");
	     List<String> titles = new ArrayList<String>();
	     titles.add("合作商订单号");
	     titles.add("缴费户号");
	     titles.add("充值金额");
	     titles.add("已充值");
	     titles.add("地区");
	     titles.add("类型");
	     titles.add("创建时间");
	     titles.add("充值状态");
	     data.setTitles(titles);
	     List<List<Object>> rows = new ArrayList<List<Object>>();
	     List<Object> row =null;
	     for (ChargeAccountBean o : lists) {
	    	 row = new ArrayList<Object>();
	    	 row.add(o.getPartner_order_no());
	    	 row.add(o.getAccount());
	    	 row.add(o.getAmount());
	    	 int charge_amount=chargeAccountService.getChargeSuccAmountById(o.getId());
	    	 row.add(charge_amount);
	    	 row.add(o.getArea());
	    	 String type="住宅";
	    	 if(o.getType()==2)type="店铺";
	    	 else if(o.getType()==3)type="企事业";
	    	 row.add(type);
	    	 row.add(DateTimeUtil.unixTime2DateStr(o.getCreate_time()));
	    	 String charge_status="未充值";
	    	 if(o.getCharge_status()==-1)charge_status="充值失败";
	    	 else if(o.getCharge_status()==1)charge_status="部分充值";
	    	 else if(o.getCharge_status()==2)charge_status="充值成功";
	    	 row.add(charge_status);
	    	 rows.add(row);
	     }
	     data.setRows(rows);
	     ExportExcelUtil.exportExcel(res,"充值列表.xlsx",data);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/list.html")
	public Map list(HttpServletRequest req, HttpServletResponse res,int page,int limit,ChargeAccountBean chargeAccount) {
		ChargeAccountBean queryModel=new ChargeAccountBean();
		PartnerBean puser=(PartnerBean) req.getSession().getAttribute("puser");
		queryModel.setPartner_id(puser.getId());
		if(!StringUtils.isEmpty(chargeAccount.getAccount()))queryModel.setAccount(chargeAccount.getAccount());
		if(chargeAccount.getType()!=null)queryModel.setType(chargeAccount.getType());
		if(chargeAccount.getCharge_status()!=null)queryModel.setCharge_status(chargeAccount.getCharge_status());
		if(chargeAccount.getNotify_status()!=null)queryModel.setNotify_status(chargeAccount.getNotify_status());
		PageInfo<ChargeAccountBean> pageInfo=chargeAccountService.pageList(queryModel, page, limit);
		return ResultUtil.getQuerySuccessResult(pageInfo);
	}
	
	
	@RequestMapping("/listPage.html")
    public ModelAndView listPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav) {
		mav.setViewName("partner/charge/list");
		return mav;
    }
	
	@ResponseBody
	@RequestMapping("/batchFail.html")
	public Result batchFail(HttpServletRequest request,HttpServletResponse response){
		Result result=new Result();
		PartnerBean puser=(PartnerBean) request.getSession().getAttribute("puser");
		int count=chargeAccountService.batchFailByPartnerId(puser.getId());
		result.setCode(0);
		result.setMsg("操作成功,更新"+count+"条数据");
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/importOrder.html")
	public Result importData(HttpServletRequest req,HttpServletResponse res,@RequestParam MultipartFile file) {
		PartnerBean puser=(PartnerBean) req.getSession().getAttribute("puser");
		Result result = new Result();
		try {
			String notify_url=HttpUtil.getServerPath(req)+"api/testPartnerNotifyUrl.html";
			InputStream inputStream = file.getInputStream();
			List<List<Cell>> list = ExcelUtil.getBankListByExcel(inputStream,file.getOriginalFilename());
			inputStream.close();
			int num = 0;
			for (int i = 0; i < list.size(); ++i) {
				try {
					List<Cell> lo = list.get(i);
					String account = ExcelUtil.getStringValueFromCell((Cell) lo.get(0));
					String amount = ExcelUtil.getStringValueFromCell((Cell) lo.get(1));
					String area = ExcelUtil.getStringValueFromCell((Cell) lo.get(2));
					//String type = ExcelUtil.getStringValueFromCell((Cell) lo.get(3));
					int type=1;
					int status=-1;
					if (!StringUtils.isEmpty(account)&&!StringUtils.isEmpty(amount)&&!StringUtils.isEmpty(area)) {
						account=account.trim();
						area=area.trim();
						ChargeAccountBean insertModel = new ChargeAccountBean();
						account=account.trim();
						insertModel.setPartner_order_no(PassWrodsCreater.getUUIDStr());
						insertModel.setPartner_id(puser.getId());
						AreaBean phoneArea=new AreaBean();
						phoneArea.setArea(area);
						List<AreaBean> areaList=phoneAreaService.queryList(phoneArea);
						if(areaList==null||areaList.size()==0)
						{
							status=-2;
							insertModel.setRemarks("不支持的缴费地区");
						}
						else
						{
							insertModel.setArea_code(areaList.get(0).getArea_code());
						}
						insertModel.setArea(area);
						insertModel.setAccount(account);
						insertModel.setAmount(Integer.parseInt(amount));
						insertModel.setStatus(status);
						insertModel.setType(type);
						insertModel.setNotify_url(notify_url);
						insertModel.setCreate_time(System.currentTimeMillis()/1000);
						insertModel.setUpdate_time(insertModel.getCreate_time());
						chargeAccountService.insert(insertModel);
						num++;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
			}
			if(num>0) {
				OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			}
			result.setCode(0);
			result.setMsg("上传成功,上传" + num + "条数据");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("上传失败" + e.getMessage());
			return result;
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/cancel.html")
	public Result cancel(HttpServletRequest request,HttpServletResponse response,Long id) throws IOException {
		Result result=new Result();
		try {
			ChargeAccountBean chargeAccount=chargeAccountService.getById(id);
			if(chargeAccount==null)
			{
				result.setCode(1);
				result.setMsg("订单不存在");
				return result;
			}
			if(chargeAccount.getCharge_status()==2||chargeAccount.getStatus()==-3)
			{
				result.setCode(1);
				result.setMsg("该订单状态不可取消");
				return result;
			}
			OrderBean lastOrder=orderService.getLastByChargeAccountId(chargeAccount.getId());
			if(lastOrder!=null&&lastOrder.getCreate_time()>System.currentTimeMillis()/1000-GlobalConfig.query_time_out)
			{
				result.setCode(1);
				result.setMsg("该订单正在充值中，不可取消");
				return result;
			}
			ChargeAccountBean updateModel=new ChargeAccountBean();
			updateModel.setId(chargeAccount.getId());
			updateModel.setStatus(-3);
			updateModel.setRemarks("手动取消");
			updateModel.setUpdate_time(System.currentTimeMillis()/1000);
			chargeAccountService.update(updateModel);
			result.setCode(0);
			result.setMsg("操作成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
	@RequestMapping(value = "/addPage.html")
	public ModelAndView addPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav) throws IOException {
		mav.setViewName("partner/charge/add");
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/add.html")
	public Result add(HttpServletRequest request,HttpServletResponse response) throws IOException {
		Result result=new Result();
		PartnerBean puser=(PartnerBean) request.getSession().getAttribute("puser");
		String account=request.getParameter("account");
		String amount=request.getParameter("amount");
		String area=request.getParameter("area");
		String type=request.getParameter("type");
		PartnerBean partner=partnerService.getById(puser.getId());
		String partner_id=String.valueOf(partner.getId());
		String partner_order_no=PassWrodsCreater.getUUIDStr();
		String notify_url=HttpUtil.getServerPath(request)+"api/testPartnerNotifyUrl.html";
		String sign=MD5.getMD5(partner_id+partner_order_no+account+amount+type+area+notify_url+partner.getApi_key());
		Map<String,String> param=new HashMap<String,String>();
		param.put("partner_id", partner_id);
		param.put("partner_order_no", partner_order_no);
		param.put("account", account);
		param.put("amount", amount);
		param.put("type", type);
		param.put("area", area);
		param.put("notify_url", notify_url);
		param.put("sign", sign);
		Response res=Http.create(HttpUtil.getServerPath(request)+"api/receiveOrder").body(param).post().send().getResponse();
		if(res.getStatus()==0)
		{
			result.setCode(0);
			result.setMsg("网络异常");
			result.setData("");
			return result;
		}
		JSONObject json=JSONObject.fromObject(res.getResult());
		result.setCode(json.getInt("code"));
		result.setMsg(json.getString("msg"));
		result.setData("");
		return result;
	}
}
